package com.zy.socket.exampls;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @Author Gong
 * @Description 2.客户端发送内容给服务端，服务端给予反馈
 * @dATE 2021/12/16 11:01
 **/
public class Client2 {
    public static void main(String[] args) {
        OutputStream outputStream =null;
        Socket socket =null;
        try {
             socket = new Socket(InetAddress.getByName("127.0.0.1"),8989);
           outputStream = socket.getOutputStream();
            outputStream.write("我是客户端".getBytes());
            //如果没有这句话，不能正常结束，服务器将一直阻塞
            socket.shutdownOutput();

            InputStream inputStream = socket.getInputStream();
            byte[] b= new byte[1024];
            int len;
            while((len = inputStream.read(b)) != -1){
                String res = new String(b,0,len);
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
